package org.example.servletpractice.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "SessionServlet", value = "/sessionServlet")
public class SessionServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果不存在session对象则创建一个session对象
        HttpSession session = req.getSession(true);
        //获取session创建时间
        //设置日期输出的格式
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(session.getCreationTime());
        Date date1 = new Date(session.getLastAccessedTime());
        System.out.println("session创建时间: "+df.format(date));
        System.out.println("最后访问时间: "+df.format(date1));

        // 设置响应内容类型
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = resp.getWriter();
        writer.println("<h1>session</h1>");
        //检测是否是新访问者
        Object userId = session.getAttribute("userId");
        if (userId==null){
            session.setAttribute("userId","小明");
            session.setAttribute("count","1");
            writer.println("<h2>欢迎首次访问: 小明</h2>");
        }else{
            Integer count = Integer.parseInt(String.valueOf(session.getAttribute("count")))+1;
            session.setAttribute("count",count);
            writer.println("<h2>欢迎再次回来: "+userId+"</h2>");
        }
        writer.println("<h2>访问次数: "+session.getAttribute("count")+"</h2>");
        writer.println("<h2>session创建时间: "+df.format(date)+"</h2>");
        writer.println("<h2>session最后访问时间: "+df.format(date1)+"</h2>");

        writer.flush();
        writer.close();
    }
}
